/*
 * Giffel, Android application
 *
 * Copyright (C) 2011  Mid Sweden University
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.appening;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerConnector {
    private Socket socket;
    private BufferedReader in;
    private OutputStream out;
    private String address;
    private int port;

    public ServerConnector(String address, int port) {
        this.address = address;
        this.port = port;
    }

    private void openConnection() {
        try {
            socket = new Socket(address, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = socket.getOutputStream();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void closeConnection() {
        try {
            in.close();
            out.flush();
            out.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getVotes(String ID) {
        openConnection();
        
        String str = "GETVOTES:" + ID + "\n";
        String response = "0";
        try {
            out.write(str.getBytes());
            response = in.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        closeConnection();
        
        return Integer.parseInt(response);
    }

    public boolean addVote(String ID) {
        openConnection();
        
        String str = "VOTE:" + ID + "\n";
        String response = "0";
        try {
            out.write(str.getBytes());
            response = in.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        closeConnection();
        
        return response.equalsIgnoreCase("OK");
    }
}
